import customtkinter
import os
from PIL import Image
from tkinter import filedialog,messagebox
import webbrowser
import public_lib
import threading as thd
import io
system_type=os.name # 获取系统类型
LOG_FILE_NAME = "LOG.log"
class App(customtkinter.CTk):
    def __init__(self):
        super().__init__()
        self.title("图片压缩V1.0.0")    # 设置窗口标题
        self.geometry("700x450")        # 设置窗口大小
        self.resizable(False, False)    # 设置窗口是否可变
        self.file_path = ''             # 图片路径
        self.folder_path = ''           # 图片文件夹路径
        self.page = ''                  # 当前页面标识
        self.folder_path_list = []      # 多图压缩文件夹路径列表
        self.img_num = 0                # 统计照片数量
        self.img_quality_get = 30       # 图片质量
        self.img_new_size_get = 1       # 图片压缩尺寸
        self.many_img_quality_get = 30  # 多图压缩质量
        self.many_img_new_size_get = 1  # 多图压缩尺寸
        self.inPath_name = ''           # 图片压缩输入路径名
        # set grid layout 1x2
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=1)
        # load images with light and dark mode image 加载图片
        image_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "img")  ## 程序路径
        self.dark_mode_image = customtkinter.CTkImage(Image.open(os.path.join(image_path, "CustomTkinter_logo_single.png")), size=(26, 26))
        self.logo_image = customtkinter.CTkImage(Image.open(os.path.join(image_path, "CustomTkinter_logo_single.png")), size=(26, 26))

        self.home_image = customtkinter.CTkImage(light_image=Image.open(os.path.join(image_path, "img_dark.png")),
                                                 dark_image=Image.open(os.path.join(image_path, "img_light.png")), size=(20, 20))
        self.chat_image = customtkinter.CTkImage(light_image=Image.open(os.path.join(image_path, "many_img_dark.png")),
                                                 dark_image=Image.open(os.path.join(image_path, "many_img_lignt.png")), size=(20, 20))
        self.add_user_image = customtkinter.CTkImage(light_image=Image.open(os.path.join(image_path, "about_dark.png")),
                                                     dark_image=Image.open(os.path.join(image_path, "about_light.png")), size=(20, 20))
        self.about_logo_img = customtkinter.CTkImage(Image.open(os.path.join(image_path, "CustomTkinter_logo_single.png")), size=(100, 100))
        self.head_img = customtkinter.CTkImage(Image.open(os.path.join(image_path, "head_img.png")), size=(10, 20))
        
        # create navigation frame 新建导航框架
        self.navigation_frame = customtkinter.CTkFrame(self, corner_radius=0)
        self.navigation_frame.grid(row=0, column=0, sticky="nsew")
        self.navigation_frame.grid_rowconfigure(4, weight=1)
        
        # logo
        self.navigation_frame_label = customtkinter.CTkLabel(self.navigation_frame, text="  图片压缩工具", image=self.logo_image,
                                                             compound="left", font=customtkinter.CTkFont(size=15, weight="bold"))
        self.navigation_frame_label.grid(row=0, column=0, padx=10, pady=10)
        
        # 单图压缩
        self.img_button = customtkinter.CTkButton(self.navigation_frame, corner_radius=0, height=40, border_spacing=10, text="单图压缩",
                                                   fg_color="transparent", text_color=("gray10", "gray90"), hover_color=("gray70", "gray30"),
                                                   image=self.home_image, anchor="w", command=self.home_button_event)
        self.img_button.grid(row=1, column=0, sticky="ew")
        
        # 多图压缩
        self.many_img_button = customtkinter.CTkButton(self.navigation_frame, corner_radius=0, height=40, border_spacing=10, text="多图压缩",
                                                      fg_color="transparent", text_color=("gray10", "gray90"), hover_color=("gray70", "gray30"),
                                                      image=self.chat_image, anchor="w", command=self.frame_2_button_event)
        self.many_img_button.grid(row=2, column=0, sticky="ew")
        
        # 关于
        self.about_button = customtkinter.CTkButton(self.navigation_frame, corner_radius=0, height=40, border_spacing=10, text="关于",
                                                      fg_color="transparent", text_color=("gray10", "gray90"), hover_color=("gray70", "gray30"),
                                                      image=self.add_user_image, anchor="w", command=self.frame_3_button_event)
        self.about_button.grid(row=3, column=0, sticky="ew")
        
        # 主题切换 
        self.appearance_mode_menu = customtkinter.CTkOptionMenu(self.navigation_frame, values=["浅色主题", "深色主题", "跟随系统"],#["亮色主题", "暗色主题", "跟随系统",'light']
                                                                anchor="center",
                                                                text_color= ("#000000","#FFFFFF"),
                                                                command=self.change_appearance_mode_event,
                                                                fg_color=("#A7A7A7","#3B8ED0"),
                                                                button_color = ("#7E7E7E","#1B6CAD"),
                                                                )
        
        self.appearance_mode_menu.grid(row=6, column=0, padx=20, pady=20, sticky="s")

        # 单图页面>>>>>>>>>>>>>>>>
        self.img_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color="transparent")
        self.img_frame.grid_columnconfigure(0, weight=1)
        self.img_entry = customtkinter.CTkEntry(self.img_frame, placeholder_text="输入图片路径",
                                                 width=300)
        self.img_entry.place(x=20,y=20)
        self.img_button_select = customtkinter.CTkButton(self.img_frame, text="选择图片",
                                                        #    width=60,
                                                        text_color =  ("#000000","#FFFFFF"),
                                                        fg_color=("#A7A7A7","#3B8ED0"),
                                                           command=self.choose_file)
        self.img_button_select.place(x=20+300+10,y=20)



        # 多图页面>>>>>>>>>>>>>>>>
        self.many_img_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color="transparent")
        self.many_img_frame.grid_columnconfigure(0, weight=1)
        self.many_img_entry = customtkinter.CTkEntry(self.many_img_frame, placeholder_text="输入文件夹路径",
                                                 width=300)
        self.many_img_entry.place(x=20,y=20)
        self.many_img_button_select = customtkinter.CTkButton(self.many_img_frame, text="选择文件夹",
                                                        #    width=60,
                                                        text_color = ("#000000","#FFFFFF"),
                                                        fg_color=("#A7A7A7","#3B8ED0"),
                                                           command=self.choose_folder)
        self.many_img_button_select.place(x=20+300+10,y=20)
        # 关于>>>>>>>>>>>>>>>>
        self.about_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color="transparent")
        self.about_frame.grid_columnconfigure(0, weight=1)
        self.about_frame_large_image_label = customtkinter.CTkLabel(self.about_frame, text="", image=self.about_logo_img)
        self.about_frame_large_image_label.grid(row=0, column=0, padx=20, pady=50)
        self.about_frame_label = customtkinter.CTkLabel(self.about_frame, text="     作者：工控万金油   ", fg_color="transparent")
        self.about_frame_label.grid(row=1, column=0, padx=20, pady=0)

        self.about_frame_label1 = customtkinter.CTkLabel(self.about_frame, text="    邮箱：i@icsteam.cn", fg_color="transparent")
        self.about_frame_label1.grid(row=2, column=0, padx=20, pady=0)
        self.about_frame_label1.bind("<Button-1>", command=self.copy_to_clipboard) # 鼠标左键点击打开浏览器
        self.mouse_display_style(self.about_frame_label1)

        self.about_frame_label2 = customtkinter.CTkLabel(self.about_frame, text="个人博客：blog.icsteam.cn", fg_color="transparent")
        self.about_frame_label2.grid(row=3, column=0, padx=20, pady=0)
        self.about_frame_label2.bind("<Button-1>", lambda e: webbrowser.open_new("blog.icsteam.cn")) # 鼠标左键点击打开浏览器
        self.mouse_display_style(self.about_frame_label2)

        self.about_frame_label3 = customtkinter.CTkLabel(self.about_frame, text="基于框架：CustomTkinter  ", fg_color="transparent")
        self.about_frame_label3.grid(row=4, column=0, padx=20, pady=0)
        self.about_frame_label3.bind("<Button-1>", lambda e: webbrowser.open_new("https://customtkinter.tomschimansky.com/")) # 鼠标左键点击打开浏览器
        self.mouse_display_style(self.about_frame_label3)

        self.about_frame_label3 = customtkinter.CTkLabel(self.about_frame, text="项目地址：https://gitee.com/icsteam/zipPicture", fg_color="transparent")
        self.about_frame_label3.grid(row=5, column=0, padx=20, pady=0)
        self.about_frame_label3.bind("<Button-1>", lambda e: webbrowser.open_new("https://gitee.com/icsteam/zipPicture")) # 鼠标左键点击打开浏览器
        self.mouse_display_style(self.about_frame_label3)

        # 图片分辨率和质量>>>>>>>>>>>>>>>>>>>>
        self.img_size_list = [None for i in range(23)]      # 单图
        self.many_img_size_list = [None for i in range(23)] # 多图

        # 选择初始化页面>>>>>>>>>>>>>>>>>>>..
        self.select_frame_by_name("img")
        # customtkinter.set_appearance_mode('dark')
        # self.appearance_mode_menu.set("暗色主题") 
        self.change_fram(self.img_size_list,self.img_frame)
        self.change_fram(self.many_img_size_list,self.many_img_frame)
    # 格式化字节显示
    def format_size(self,value):
        size = 1024 if system_type == 'nt' else 1000
        if value < size:
            return str(value) + ' B'
        elif value < size*size:
            return str(round(value/size,2)) + ' KB'
        elif value < size*size*size:
            return str(round(value/size/size,2)) + ' MB'
        elif value < size*size*size*size:
            return str(round(value/size/size/size,2)) + ' GB'
        else:
            return '***'
    # 输入框设定值
    def set_Entry_value(self,event,value):
        event.delete(0, 'end')  # 清空输入框
        event.insert(0,value)   # 设置输入框值
    # 开始压缩按钮点击事件
    def zipPicture_button_event(self,key):
        try:
            self.scale(key[8].get(),key[2].get())
        except:
            pass
    # 尺寸和大小按钮切换样式
    def switch_button_color(self,event,value,key,type):
        if type in [3,4,5,9,10,11]:
            self.set_Entry_value(event,value)
        if type in [3,4,5,100]:
            key[3].configure(fg_color="#1496FA" if type == 3 else ("gray75",'gray25'))
            key[4].configure(fg_color="#1496FA" if type == 4 else ("gray75",'gray25'))
            key[5].configure(fg_color='#1496FA' if type == 5 else ("gray75",'gray25'))
        if type in [9,10,11,101]:
            key[9].configure(fg_color="#1496FA" if type == 9 else ("gray75",'gray25'))
            key[10].configure(fg_color='#1496FA' if type == 10 else ("gray75",'gray25'))
            key[11].configure(fg_color='#1496FA' if type == 11 else ("gray75",'gray25'))
        self.scale(key[8].get(),key[2].get())
    # 重新
    def re_display_size(self,event):
        if self.page == 'img' and self.file_path != '':
            thd0 = thd.Thread(target=self.get_img_size,args=(self.img_size_list,self.file_path))
            thd0.daemon = True
            thd0.start()
            # self.get_img_size(self.img_size_list,self.file_path)
        elif self.page =='many_img' and self.folder_path_list != []:
            thd0 = thd.Thread(target=self.get_img_size,args=(self.many_img_size_list,self.folder_path_list[0]))
            thd0.daemon = True
            thd0.start()
            # self.get_img_size(self.many_img_size_list,self.folder_path_list[0])
    def change_fram(self,key,fram_index):
            key[0] = customtkinter.CTkLabel(fram_index, text="",image=self.head_img)
            key[0].place(x=10,y=20+40)

            key[1] = customtkinter.CTkLabel(fram_index, text="图片分辨率", fg_color="transparent")
            key[1].place(x=20,y=20+40)
            # 自定义输入框
            key[2] = customtkinter.CTkEntry(fram_index, placeholder_text="输入0~100，默认100",
                                                    #  width=300
                                                    )
            key[2].place(x=20+50+50+50,y=20+20+40+20)              
            key[2].bind("<KeyRelease>",self.re_display_size)
            key[2].bind("<Button-1>",command=lambda event: self.switch_button_color(key[2],"90",key,100))
            # 分辨率 大
            key[3] = customtkinter.CTkButton(fram_index, text="大",
                                                            width=30,
                                                            fg_color = ("gray75", "gray25"),
                                                            text_color = ("#242424",'#ffffff'),
                                                            text_color_disabled = ("#919191","#919191"),
                                                            command=lambda : self.switch_button_color(key[2],"90",key,3))
            key[3].place(x=20,y=20+20+40+20)
            key[3].bind("<Button-1>",self.re_display_size)

            # 分辨率 中
            key[4] = customtkinter.CTkButton(fram_index, text="中",
                                                            width=30,
                                                            fg_color = ("gray75", "gray25"),
                                                            text_color = ("#242424",'#ffffff'),
                                                            text_color_disabled = ("#919191","#919191"),
                                                            command=lambda : self.switch_button_color(key[2],"60",key,4))
            key[4].place(x=20+50,y=20+20+40+20)
            key[4].bind("<Button-1>",self.re_display_size)

            # 分辨率 小
            key[5] = customtkinter.CTkButton(fram_index, text="小",
                                                            width=30,
                                                            fg_color = ("gray75", "gray25"),
                                                            text_color = ("#242424",'#ffffff'),
                                                            text_color_disabled = ("#919191","#919191"),
                                                            command=lambda : self.switch_button_color(key[2],"30",key,5))
            key[5].place(x=20+50+50,y=20+20+40+20)
            key[5].bind("<Button-1>",self.re_display_size)    

            # 图片质量>>>>>>>>>>>>>>>>>>>>
            key[6] = customtkinter.CTkLabel(fram_index, text="",image=self.head_img)
            key[6].place(x=10,y=20+100+20)

            key[7] = customtkinter.CTkLabel(fram_index, text="图片质量", fg_color="transparent")
            key[7].place(x=20,y=20+100+20)
            # 自定义输入框
            key[8] = customtkinter.CTkEntry(fram_index, placeholder_text="输入0~100,默认100",
                                                    #  width=300
                                                    )
            key[8].place(x=20+50+50+50,y=20+100+20+40) 
            key[8].bind("<KeyRelease>",self.re_display_size)
            key[8].bind("<Button-1>",command=lambda event: self.switch_button_color(key[2],"90",key,101))
            # 质量 高
            key[9] = customtkinter.CTkButton(fram_index, text="高",
                                                            width=30,
                                                            fg_color = ("gray75", "gray25"),
                                                            text_color = ("#242424",'#ffffff'),
                                                            text_color_disabled = ("#919191","#919191"),
                                                            command=lambda: self.switch_button_color(key[8],"90",key,9))
            key[9].place(x=20,y=20+100+20+40)
            key[9].bind("<Button-1>",self.re_display_size)
            # 质量 中
            key[10] = customtkinter.CTkButton(fram_index, text="中",
                                                            width=30,
                                                            fg_color = ("gray75", "gray25"),
                                                            text_color = ("#242424",'#ffffff'),
                                                            text_color_disabled = ("#919191","#919191"),
                                                            command=lambda: self.switch_button_color(key[8],"60",key,10))
            key[10].place(x=20+50,y=20+100+20+40)
            key[10].bind("<Button-1>",self.re_display_size)
            # 质量 低
            key[11] = customtkinter.CTkButton(fram_index, text="低",
                                                            width=30,
                                                            fg_color = ("gray75", "gray25"),
                                                            text_color = ("#242424",'#ffffff'),
                                                            text_color_disabled = ("#919191","#919191"),
                                                            command=lambda: self.switch_button_color(key[8],"30",key,11))
            key[11].place(x=20+50+50,y=20+100+20+40)
            key[11].bind("<Button-1>",self.re_display_size)

            # 预览框    
            key[12] = customtkinter.CTkLabel(fram_index, 
                                                        corner_radius=10,
                                                        width=300,
                                                        height=200,
                                                        fg_color=("#ffffff","#353535"),
                                                        # bg_color =("#353535","#ffffff"),
                                                        text_color= ("#353535","#ffffff"),
                                                        text='预览框'
                                                        
                                                        )
            key[12].place(x=20,y=20+100+20+40+40)


            # 进度条
            pg_mode = ["determinate", "indeterminate"]
            key[13] = customtkinter.CTkProgressBar(fram_index, 
                                                   orientation="horizontal",
                                                #    fg_color = "#8d8d8d",
                                                #    border_color = "#8d8d8d",
                                                progress_color= ("#fcfcfc","#8d8d8d"),

                                                   mode=pg_mode[0],
                                                   width=300,
                                                #    determinate_speed=1,
                                                   indeterminate_speed=0.8
                                                   )
            key[13].place(x=20,y=20+100+20+40+40+200+10)
            key[13].set(0)
            # key[13].configure(progress_color= ("#198bce","#198bce"))
            key[14] = customtkinter.CTkButton(fram_index, text="开始压缩",
                                                            #    width=60,
                                                           text_color = ("#000000","#FFFFFF"),
                                                           fg_color=("#A7A7A7","#3B8ED0"),
                                                            command=lambda: self.zipPicture_button_event(key)
                                                            )
            key[14].place(x=20+300+10,y=20+100+20+40+40)

            key[15] = customtkinter.CTkLabel(fram_index, text="原图", anchor='w',fg_color="transparent")
            key[15].place(x=20+300+10,y=20+100+20+40+40+40)
            key[16] = customtkinter.CTkLabel(fram_index, text="尺寸：", anchor='w',fg_color="transparent")
            key[16].place(x=20+300+10,y=20+100+20+40+40+40+20)
            key[17] = customtkinter.CTkLabel(fram_index, text="大小：", anchor='w',fg_color="transparent")
            key[17].place(x=20+300+10,y=20+100+20+40+40+40+20+20)

            
            key[18] = customtkinter.CTkLabel(fram_index, text="压缩后", anchor='w',text_color=("#CE2929","#FAF608"))
            key[18].place(x=20+300+10,y=20+100+20+40+40+40+20+40+10)
            key[19] = customtkinter.CTkLabel(fram_index, text="尺寸：", anchor='w',text_color=("#CE2929","#FAF608"))
            key[19].place(x=20+300+10,y=20+100+20+40+40+40+20+40+20+10)
            key[20] = customtkinter.CTkLabel(fram_index, text="大小：", anchor='w',text_color=("#CE2929","#FAF608"))
            key[20].place(x=20+300+10,y=20+100+20+40+40+40+20+40+20+20+10)
            key[21] = customtkinter.CTkLabel(fram_index, text="", 
                                             anchor='center',
                                             width= 120,
                                             text_color=("#CE2929","#FAF608"))
            key[21].place(x=20+300+10,y=20+100+20+40+40+40+20+40+20+20+10+30)
            # 处理进度
            key[22] = customtkinter.CTkLabel(fram_index, text="", 
                                             anchor='w',
                                             width= 120,
                                             text_color=("#CE2929","#FAF608"))
            key[22].place(x=20+300+10,y=20+100+20+40+40+40+20+40+20+20+10+30+20)
    def scale(self,quality,new_size):
        try:
            quality = int(quality if quality != '' else 100)
        except:
            quality = 100
        try:
            new_size = int(new_size if new_size != '' else 100)
        except:
            new_size = 100
        if quality > 100:
            quality = 100
        if quality <0 :
            quality = 1
        if new_size > 100:
            new_size = 1
        elif new_size <= 0:
            new_size = 1
        else:
            new_size = new_size / 100
        if self.page == 'img':
            self.img_quality_get = quality
            self.img_new_size_get = new_size
        elif self.page =='many_img':
            self.many_img_quality_get = quality
            self.many_img_new_size_get = new_size
        return quality,new_size
    # 判断处理后的文件大小
    def compress_image(self,input_image_path, output_image_path, quality=10,new_size=1):
        quality,new_size = self.scale(quality,new_size)
        with Image.open(input_image_path) as image:
            buffer = io.BytesIO()   #创建内存缓冲区
            image.getexif()         # 获取图片的exif信息
            icc_profile = image.info.get("icc_profile")  # 获取原图ICC配置文件
            exif_bytes = image.getexif().tobytes()       # 将EXIF数据写回图像文件
            original_size = image.size  # 获取图片的原始大小
            ratio = new_size            # 计算等比例缩放后的大小
            new_size = (int(original_size[0] * ratio), int(original_size[1] * ratio))
            resized_img = image.resize(new_size, Image.Resampling.LANCZOS)  # 等比例缩放图片
            img_type = input_image_path.split('.')[-1]                      # 获取图片后缀名
            if img_type in ['jpg','JPG','jpeg','JPEG']:
                img_type = 'jpeg' 
            if img_type in ['jpg','JPG','webp','WEBP','jpeg','JPEG'] :
                save_kwargs = {
                    'exif':exif_bytes, # 写入EXIF数据
                    'quality':quality, # 设置压缩质量
                    'optimize':True,    # 优化压缩
                    'icc_profile':icc_profile, # 写入ICC配置文件
                    'format':img_type,
                    }
            else:
                if resized_img.mode == 'RGBA':
                    resized_img = resized_img.convert('RGB')
                save_kwargs = {
                    'exif':exif_bytes, # 写入EXIF数据
                    'quality':quality, # 设置压缩质量
                    'optimize':True,    # 优化压缩
                    'format':'jpeg' if resized_img.mode == 'RGB'  else img_type,
                    'reduce_colors':True,
                    'icc_profile':icc_profile, # 写入ICC配置文件
                    }
            resized_img.save(buffer, # 保存压缩后的图片
                              **save_kwargs)  # 设置压缩质量 
        file_original_size = os.path.getsize(input_image_path)
        file_new_size = buffer.getbuffer().nbytes
        return self.format_size(file_original_size), original_size,self.format_size(file_new_size), new_size # 原来文件大小、尺寸、压缩后文件大小、尺寸
    # 匹配预览框尺寸图片
    def resize_by_img(self,input_path, target_height,target_width=None):
        img = Image.open(input_path)                # 读取图片
        original_width, original_height = img.size  # 获取图片的原始尺寸
        # 计算缩放比例
        ratio = target_height / original_height
        new_width = int(original_width * ratio)
        new_height = target_height
        if new_width > target_width:
            ratio = target_width / original_width
            new_width = target_width
            new_height = int(original_height * ratio)
        # 缩放图片并保存
        resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
        return resized_img,(new_width, new_height)
    # 鼠标模式
    def mouse_display_style(self, case):
        case.bind("<Enter>", lambda event: case.configure(cursor='hand2')) # 鼠标指针进入时显示手型
        case.bind("<Leave>", lambda event: case.configure(cursor='arrow')) # 鼠标指针离开时显示标准箭头型    
    # 复制邮箱    
    def copy_to_clipboard(self, event):
        text = 'i@icsteam.cn'       # 获取 Text 小部件的内容
        self.clipboard_clear()      # 清空剪贴板
        self.clipboard_append(text) # 复制内容到剪贴板
        messagebox.showinfo("提示", f"已将 {text} 复制到剪贴板") # 弹出提示窗口
    # 选择页面
    def select_frame_by_name(self, name):
        # set button color for selected button
        self.img_button.configure(fg_color=("gray75", "gray25") if name == "img" else "transparent")
        self.many_img_button.configure(fg_color=("gray75", "gray25") if name == "many_img" else "transparent")
        self.about_button.configure(fg_color=("gray75", "gray25") if name == "about" else "transparent")
        self.page = name        # 记录当前页面标识
        # show selected frame
        if name == "img":
            self.img_frame.grid(row=0, column=1, sticky="nsew")
        else:
            self.img_frame.grid_forget()
        if name == "many_img":
            self.many_img_frame.grid(row=0, column=1, sticky="nsew")
        else:
            self.many_img_frame.grid_forget()
        if name == "about":
            self.about_frame.grid(row=0, column=1, sticky="nsew")
        else:
            self.about_frame.grid_forget()
    def home_button_event(self):
        self.select_frame_by_name("img")
    def frame_2_button_event(self):
        self.select_frame_by_name("many_img")
    def frame_3_button_event(self):
        self.select_frame_by_name("about")
    # 切换主题
    def change_appearance_mode_event(self, new_appearance_mode):
        appearance_mode = {"浅色主题":"light","深色主题":"dark","跟随系统":"system"}
        customtkinter.set_appearance_mode(appearance_mode[new_appearance_mode])
    # 获取图片原始和压缩后大小方法
    def get_img_size(self,fram_index,file_path):
        self.inPath_name = file_path
        fram_index[13].configure(mode="indeterminate")
        fram_index[13].start()
        try:    
            info = self.compress_image(file_path, 
                                f'temp.{file_path.split(".")[-1]}', #参数未起作用，改用缓存
                                quality=fram_index[8].get(),
                                new_size=fram_index[2].get()
                                    )
        except Exception as e:
            messagebox.showinfo("错误", f"检查图片格式是否正确！\n错误码：{e}")
        # os.remove(f'temp.{file_path.split(".")[-1]}')
        fram_index[13].stop()
        fram_index[13].configure(mode="determinate")
        if self.page =='many_img' :
            fram_index[15].configure(text=f"原图（首张）")
        fram_index[16].configure(text=f"尺寸：{info[1][0]}*{info[1][1]}")
        fram_index[17].configure(text=f"大小：{info[0]}")
        fram_index[19].configure(text=f"尺寸：{info[3][0]}*{info[3][1]}")
        fram_index[20].configure(text=f"大小：{info[2]}") 
    # 选择文件
    def choose_file(self):
        try:
            self.file_path = filedialog.askopenfilename()       # 选择文件
            self.set_Entry_value(self.img_entry,self.file_path) # 文件路径复制到输入框
            self.img_size_list[12].configure(text="")           # 清空预览框文本
            tmg_img,size = self.resize_by_img(self.file_path, 180,280) # 缩放图片放到预览框
            self.choose_img = customtkinter.CTkImage(tmg_img,size=size)
            self.img_size_list[12].configure(image=self.choose_img)    # 显示图片
            # 开启获取原始图片大小和压缩后图片大小的线程
            thd0 = thd.Thread(target=self.get_img_size,args=(self.img_size_list,self.file_path))
            thd0.daemon= True
            thd0.start()
        except Exception as e:
            public_lib.info(LOG_FILE_NAME,0,f"方法（choose_file）出错",e)
            messagebox.showinfo("错误", f"检查图片格式是否正确！\n错误码：{e}")

    # 选择文件夹
    def choose_folder(self):
        img_type = ['jpg','png','JPG','PNG','webp','WEBP','jpeg','JPEG']    # 
        try:
            self.folder_path = filedialog.askdirectory()               # 选择文件夹
            self.set_Entry_value(self.many_img_entry,self.folder_path) # 文件夹路径复制到输入框
            self.many_img_size_list[12].configure(text="")             # 清空预览框文本
            self.folder_path_list = public_lib.get_filePath(self.folder_path,1)  # 获取当前目录下的所有图片路径
            self.folder_path_list = [i for i in self.folder_path_list if i.split('.')[-1] in img_type] # 筛选图片

            tmg_img,size = self.resize_by_img(self.folder_path_list[0], 180,280) # 缩放图片放到预览框

            self.choose_img2 = customtkinter.CTkImage(tmg_img,size=size)
            self.many_img_size_list[12].configure(image=self.choose_img2)

            thd0 = thd.Thread(target=self.get_img_size,args=(self.many_img_size_list,self.folder_path_list[0]))
            thd0.daemon= True
            thd0.start()

            # 统计照片数并显示  
            self.img_num = len(self.folder_path_list)
            # # self.many_img_frame
            self.many_img_size_list[21].configure(text=f"共有{self.img_num}张图片")
        except Exception as e:
            public_lib.info(LOG_FILE_NAME,0,f"方法（choose_folder）出错",e)

            # print("未选择文件夹")
if __name__ == "__main__":
    app = App()
    app.mainloop()

